// miniprogram/pages/myInfo/myInfo.js
import area_list from '../../area' //从本地路径导入地区文件
const db = wx.cloud.database()
Page({

    /**
	 * 页面的初始数据
	 */
    data: {
        userAvatarUrl: 'cloud://take-out-9gg0dhd7c2f86b6b.7461-take-out-9gg0dhd7c2f86b6b-1304355002/index/images/用户头像.png',
        userName: '',
        userid: '',
        sexPicker: ['先生', '女士'],
        chooseSex: false,
        chooseBirthday: false,
        chooseCity: false,
        sex: '',
        birthday: '',
        errorMessage: '',
        telephone: '',
        address: '',
        areaList: area_list,
        city: '',
        currentDate: new Date().getTime(),
        maxDate: new Date().getTime(),
        minDate: new Date('1950/1/1').getTime(),
        formatter(type, value) {
            if (type === 'year') {
                return `${value}年`;
            } else if (type === 'month') {
                return `${value}月`;
            } else if (type === 'day') {
                return `${value}日`;
            }
            return value;
        },
    },
    checkErrors: function(event) {
        if (event.detail.length != 11) {
            this.setData({
                errorMessage: '手机长度不正确',
            })
        } else {
            this.setData({
                errorMessage: '',
            })
        }
    },
    birthdayPicker: function(event) {
        let newTime = new Date(event.detail);
        let newYear = new Date(event.detail).getFullYear();
        let newMonth = new Date(event.detail).getMonth();
        let newDate = new Date(event.detail).getDate();
        console.log('选择的日期是' + newTime + '，转化为年月日是：' + newYear + '年' + newMonth + 1 + '月' + newDate + '日')
        let birthday = JSON.stringify(newYear + '年' + newMonth + 1 + '月' + newDate + '日').replace(/\"/g,
            '');
        console.log(birthday)
        this.setData({
            chooseBirthday: false,
            birthday: birthday
        })
    },
    sexPicker: function(event) {
        this.setData({
            chooseSex: false,
            sex: event.detail.value
        })
    },
    cityPicker: function(event) {
        let city = ''
        for (let i = 0; i < 3; i++) {
            let n = event.detail.values[i].name
            city += n
        }
        this.setData({
            chooseCity: false,
            city: city
        })
    },
    chooseAddress: function() {
        wx.chooseAddress({}).then(res => {
            console.log(res)
            let city = res.provinceName + res.cityName + res.countyName
            this.setData({
                userName: res.userName,
                telephone: res.telNumber,
                city: city,
                address: res.detailInfo
            })
        })
    },
    chooseCity: function() {
        this.setData({
            chooseCity: true
        })
    },
    chooseBirthday: function() {
        this.setData({
            chooseBirthday: true
        })
    },
    chooseSex: function() {
        this.setData({
            chooseSex: true
        })
    },
    popupClose: function() {
        this.setData({
            chooseSex: false,
            chooseBirthday: false,
            chooseCity: false
        })
    },
    getWXAvatar: function() {
        wx.getUserInfo({}).then(res => {
            this.setData({
                userAvatarUrl: res.userInfo.avatarUrl,
            })
        })
    },
    sumitInfo: function() {
        wx.showLoading({
            title: '提交中',
        })
        wx.login({
            success: (res) => {
                wx.request({
                    url: 'https://api.weixin.qq.com/sns/jscode2session',
                    data: {
                        appid: 'wx01e28c48e0ec70e4',
                        secret: '17f9cf1122e62876a5318d6ef653a59e',
                        js_code: res.code,
                        grant_type: 'authorization_code'
                    },
                    success: (resa) => {
                        db.collection('user').where({
                            _openid: resa.data.openid
                        }).get({
                            success: (res) => {
                                console.log(res.data[0]._id)
                                db.collection('user').doc(res.data[0]
                                    ._id).update({
                                    data: {
                                        name: this.data
                                            .userName,
                                        sex: this.data.sex,
                                        birthday: this.data
                                            .birthday,
                                        telephone: this.data
                                            .telephone,
                                        city: this.data.city,
                                        address: this.data
                                            .address,
                                        avatarurl: this.data
                                            .userAvatarUrl
                                    }
                                })
                                wx.showModal({
                                    itle: '成功',
                                    content: '提交完毕',
                                    showCancel: false,
                                    confirmText: '确定',
                                })
                                wx.hideLoading({})
                            },
                            fail: (err) => {
                                wx.showModal({
                                    itle: '失败',
                                    content: '提交失败，请重试',
                                    showCancel: false,
                                    confirmText: '确定',
                                })
                                wx.hideLoading({})
                            }
                        })
                    },
                    fail: (err) => {
                        wx.showModal({
                            itle: '失败',
                            content: '提交失败，请重试',
                            showCancel: false,
                            confirmText: '确定',
                        })
                        wx.hideLoading({})
                    }
                })
            },
            fail: (err) => {
                wx.showModal({
                    itle: '失败',
                    content: '提交失败，请重试',
                    showCancel: false,
                    confirmText: '确定',
                })
                wx.hideLoading({})
            }
        })
    },
    /**
	 * 生命周期函数--监听页面加载
	 */
    onLoad: function(options) {
        wx.showLoading({
            title: '加载中',
        })
        db.collection('user').where({
            _openid: wx.getStorageSync('openid') // 填入当前用户 openid
        }).get({
            success: (res) => {
                this.setData({
                    userAvatarUrl: res.data[0].avatarurl,
                    userid: res.data[0].userid,
                    userName: res.data[0].name,
                    sex: res.data[0].sex,
                    birthday: res.data[0].birthday,
                    telephone: res.data[0].telephone,
                    city: res.data[0].city,
                    address: res.data[0].address
                })
                wx.hideLoading({})
            },
            fail: (err) => {
                console.error;
                wx.showModal({
                    itle: '失败',
                    content: '提交失败，请重试',
                    showCancel: false,
                    confirmText: '确定',
                })
                wx.hideLoading({})
            }
        })
    },

    /**
	 * 生命周期函数--监听页面初次渲染完成
	 */
    onReady: function() {

    },

    /**
	 * 生命周期函数--监听页面显示
	 */
    onShow: function() {

    },

    /**
	 * 生命周期函数--监听页面隐藏
	 */
    onHide: function() {

    },

    /**
	 * 生命周期函数--监听页面卸载
	 */
    onUnload: function() {

    },

    /**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
    onPullDownRefresh: function() {

    },

    /**
	 * 页面上拉触底事件的处理函数
	 */
    onReachBottom: function() {

    },

    /**
	 * 用户点击右上角分享
	 */
    onShareAppMessage: function() {

    }
})
